const Router = require('@koa/router')
const mongoose = require('mongoose')
const { v4: uuidv4 } = require('uuid');
const path = require('path')
const { saveFileToDisk, getUploadFileExt } = require('../utils/upload')
const config = require('../project.config.js')
const fs = require('fs');

const File = mongoose.model('File');
const router = new Router({
    prefix: '/upload'
})
router.post('/file', async (ctx) => {
    const ext = getUploadFileExt(ctx)
    // const filename = `${uuidv4()}.${ext}`;
    const filename = ctx.request.files.file.name
    await saveFileToDisk(ctx, path.resolve(config.UPLOAD_DIR, filename))
    console.log('当前后缀名', ext);
    if (ext === 'pdf') {
        //pdf结尾 文件名存入数据库
        // const one = await File.find({
        //     filename: filename
        // })
        // if (one) {
        //     ctx.body = {
        //         msg: "已经上传过改文件，无法再次上传",
        //         code: 0
        //     }
        //     return
        // }
        const file = new File({
            filename: filename
        })
        const res = await file.save()
        ctx.body = {
            data: res,
            msg: '文件上传到数据库成功！',
            code: 200
        }
        return
    }
    ctx.body = {
        data: filename,
        msg: '',
        code: 200
    }
})
// router.post('/file', async (ctx) => {
//     // console.log('打印当前file', file);
//     const file = ctx.request.files.file;  // 获取上传文件
//     const reader = fs.createReadStream(file.path);  // 创建可读流
//     const ext = file.name.split('.').pop();     // 获取上传文件扩展名
//     const upStream = fs.createWriteStream(`upload/${Math.random().toString()}.${ext}`);     // 创建可写流
//     reader.pipe(upStream);  // 可读流通过管道写入可写流
//     return ctx.body = '上传成功';
// })

module.exports = router